package com.linkage.jz.bankruptcy.fragment.Project;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.Project.CreateProTalkActivity;
import com.linkage.jz.bankruptcy.activity.Project.ManagerListActivity;
import com.linkage.jz.bankruptcy.activity.Project.ManagerUserPermissionActivity;
import com.linkage.jz.bankruptcy.activity.Project.OtherUserDetailActivity;
import com.linkage.jz.bankruptcy.adapter.ProManagerListViewAdapter;
import com.linkage.jz.bankruptcy.adapter.ProManagerSelListViewAdapter;
import com.linkage.jz.bankruptcy.bean.ManagerGroupInfo;
import com.linkage.jz.bankruptcy.bean.ManagerUserInfo;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.widget.CreateUserDialog;
import com.linkage.jz.bankruptcy.widget.Divider;
import com.linkage.jz.bankruptcy.widget.PublicNoticeDialog;
import com.linkage.jz.bankruptcy.widget.ShapeLoadingDialog;
import com.linkage.seapeak.activity.message.MultiSelectActivity;

import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import cn.bingoogolapple.androidcommon.adapter.BGAOnItemChildClickListener;
import cn.bingoogolapple.androidcommon.adapter.BGAOnItemChildLongClickListener;
import cn.bingoogolapple.androidcommon.adapter.BGAOnRVItemClickListener;
import cn.bingoogolapple.androidcommon.adapter.BGAOnRVItemLongClickListener;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static com.chad.library.adapter.base.listener.SimpleClickListener.TAG;


/**
 * date : 2016/5/24
 * author : lijiawei
 */
public class ProManagerSelListFrgment extends Fragment implements BGAOnRVItemClickListener, BGAOnRVItemLongClickListener, BGAOnItemChildClickListener, BGAOnItemChildLongClickListener {

    //显示信息
    private TextView text;
    //    private static final String TAG = RecyclerViewDemoActivity.class.getSimpleName();
    private ProManagerSelListViewAdapter mAdapter;
    private ArrayList<ManagerUserInfo> mData;
    private RecyclerView mDataRv;
    private EditText law_searchtxt;
    private String mProID;
    private ShapeLoadingDialog shapeLoadingDialog ;

    private CreateUserDialog createUserDialog;
    ArrayList<Fragment> fragments = new ArrayList<Fragment>();


    private String groupid;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_law_list, container, false);
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        init(view);
        initRecyclerView(view);
        shapeLoadingDialog = new ShapeLoadingDialog(getActivity());
        Bundle bundle =this.getArguments();//得到从Activity传来的数据

        if(bundle!=null){
            mProID = bundle.getString("proid");
        }

        getData();


    }

    private void init(View view) {
//        text = (TextView) view.findViewById(R.id.fragment_textview);
//        text.setText("GroupChildrenHasBuy");
    }

    private void initRecyclerView(final View view) {
        mDataRv = (RecyclerView) view.findViewById(R.id.rv_recyclerview_data);
        mDataRv.addItemDecoration(new Divider(getActivity()));
        law_searchtxt = (EditText) view.findViewById(R.id.law_searchtxt);
        law_searchtxt.setOnEditorActionListener(new TextView.OnEditorActionListener(){
            @Override

            public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {

// TODO Auto-generated method stub

                if(arg1 == EditorInfo.IME_ACTION_SEARCH)

                {
                    InputMethodManager imm = (InputMethodManager) view.getContext()
                            .getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm != null) {
                        imm.hideSoftInputFromWindow(view.getWindowToken(),0);
                    }
                    mData.clear();
                                mAdapter.notifyDataSetChanged();

                    getData();
//                    Toast.makeText(AddMemberActivity.this,"呵呵",Toast.LENGTH_SHORT).show();

// search pressed and perform your functionality.

                }

                return false;

            }

        });

        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mDataRv.setLayoutManager(layoutManager);

        mAdapter = new ProManagerSelListViewAdapter(mDataRv,getActivity());
        mAdapter.setOnRVItemClickListener(this);
        mAdapter.setOnRVItemLongClickListener(this);
        mAdapter.setOnItemChildClickListener(this);
        mAdapter.setOnItemChildLongClickListener(this);

        mDataRv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (RecyclerView.SCROLL_STATE_DRAGGING == newState) {
                    mAdapter.closeOpenedSwipeItemLayoutWithAnim();
                }
            }
        });
        mData = new ArrayList<ManagerUserInfo>();
        mAdapter.setData(mData);
        mDataRv.setAdapter(mAdapter);
    }

    @Override
    public void onItemChildClick(ViewGroup parent, View childView, int position) {
        if (childView.getId() == R.id.tv_item_bgaswipe_delete) {
            mAdapter.closeOpenedSwipeItemLayoutWithAnim();
            ManagerUserInfo infoTmp = mData.get(position);
            if(infoTmp.getCurType()== 1)
            {
                //删除用户
                delUser(infoTmp.getId());
            }else{
                //删除群组
                delGroup(infoTmp.getGroup().getId());
            }
        }

        if (childView.getId() == R.id.tv_item_bgaswipe_edit) {
            mAdapter.closeOpenedSwipeItemLayoutWithAnim();
            ManagerUserInfo model = mData.get(position);
            Intent intent = new Intent(getActivity(), OtherUserDetailActivity.class);
            intent.putExtra("info",new Gson().toJson(model));
            getActivity().startActivity(intent);
//            ManagerUserInfo infoTmp = mData.get(position);
//            groupid = infoTmp.getGroup().getId();
//            createUserDialog = new CreateUserDialog(getActivity(),onClickListener);
//            createUserDialog.show();
        }

        if(childView.getId() == R.id.iv_manageuser_add)
        {
            ManagerUserInfo infoTmp = mData.get(position);
            groupid = infoTmp.getGroup().getId();
            createUserDialog = new CreateUserDialog(getActivity(),onClickListener);
            createUserDialog.show();
        }
    }

    @Override
    public boolean onItemChildLongClick(ViewGroup parent, View childView, int position) {
        if (childView.getId() == R.id.tv_item_bgaswipe_delete) {

            return true;
        }
        if(childView.getId() == R.id.tv_item_bgaswipe_edit) {

            return true;
        }


        return false;
    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            switch (v.getId()) {

                case R.id.btn_chancel_u:
                    createUserDialog.dismiss();
                    break;
                case R.id.btn_save_u:
                    String name = createUserDialog.text_name_u.getText().toString().trim();
                    String phone = createUserDialog.text_mobile_u.getText().toString().trim();
                    addUser(groupid,name,phone);
                    break;

            }
        }
    };


    @Override
    public void onRVItemClick(ViewGroup parent, View itemView, int position) {
        ManagerUserInfo model = mAdapter.getItem(position);
        if(model !=null) {

            if(model.getCurType()==1)
            {

//                Intent intent = new Intent(getActivity(), CreateProTalkActivity.class);
//                intent.putExtra("seluserName", model.getUser().getUsername());
//                intent.putExtra("seluserId", model.getId());
//                intent.putExtra("selsysuserId", model.getSysUserId());
//                getActivity().setResult(getActivity().RESULT_OK, intent);
//                getActivity().finish();
                BankruptcyApp.getInstance().selManger =model;
                mAdapter.notifyDataSetChanged();
//                mAdapter.notifyAll();


            }


        }

    }
    int sumNum = 0;
    @Override
    public boolean onRVItemLongClick(ViewGroup parent, View itemView, int position) {
//        Toast.makeText(getActivity(), "长按了条目 " + mAdapter.getItem(position).getTitle(), Toast.LENGTH_SHORT).show();
        return true;
    }


    public void getData()
    {
        if(BankruptcyApp.tokeninfo == null|| BankruptcyApp.tokeninfo.getToken() == null)
        {
            return;
        }
//        shapeLoadingDialog.setLoadingText("加载中...");
//        shapeLoadingDialog.setCanceledOnTouchOutside(false);
//        shapeLoadingDialog.show();
        OkHttpClient okHttpClient = new OkHttpClient();
//        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong()+"";
        String timestamp =System.currentTimeMillis()+"";
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken","");
        String userId = SPUtils.getInstance(Consts.SPNAME).getString("userId","");

        String title = law_searchtxt.getText().toString();

        RequestBody requestBody = new FormBody.Builder()
                .add("appid","1000000001")
                .add("nonce",rom)
                .add("timestamp", timestamp)
                .add("projectId",mProID)
                .add("token", BankruptcyApp.tokeninfo.getToken())
                .add("userToken", userToken)
                .add("searchName",title)
                .add("pageNumber","1")
                .add("pageSize","100")
                .build();

        String url = Consts.WEBURL_MANAGERSLIST;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                shapeLoadingDialog.dismiss();
//                Log.d(TAG, "onFailure: " + e.getMessage());
//                runOnUiThread(new Runnable(){
//
//                    @Override
//                    public void run() {
//                        //更新UI
//                        Toast.makeText(PersonSettingOrgActivity.this,"保存失败",Toast.LENGTH_SHORT).show();
//
//                    }
//
//                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

//                shapeLoadingDialog.dismiss();


                String str = response.body().string();

                try{
                    JSONObject object = new JSONObject(str);
                    mData.clear();
                    if (object.optInt("code") == 0) {
                        ManagerGroupInfo managerGroupInfo = new Gson().fromJson(object.optString("data"), ManagerGroupInfo.class);
                        List<ManagerUserInfo> list = new ArrayList<>();
                        sumNum = 0;

                        HashMap<String, ManagerUserInfo> groupTemp = new HashMap<>();
                        for (ManagerGroupInfo.GroupListBean bean : managerGroupInfo.getGroupList()) {
                            for (ManagerUserInfo info : bean.getList()){
                                if (info.getGroup() != null && !groupTemp.containsKey(info.getGroup().getId())) {
                                    info.setCurType(0);
                                    groupTemp.put(info.getGroup().getId(), info);
                                    list.add(info);
                                }

                                if (info.getUser() != null) {
                                    ManagerUserInfo tempUser;
                                    tempUser = new Gson().fromJson(new Gson().toJson(info), ManagerUserInfo.class);
                                    tempUser.setCurType(1);

                                    list.add(tempUser);
                                }
                            }
                        }

                        for (ManagerGroupInfo.GroupCountBean bean : managerGroupInfo.getGroupCount()) {
                            sumNum += bean.getCnt();
                            if (groupTemp.containsKey(bean.getId()))
                                groupTemp.get(bean.getId()).setGroupnum(bean.getCnt());
                        }

//                        Iterator<String> it = groupListobj.keys();
//                        List<ManagerUserInfo> list = new ArrayList<>();
//                        while (it.hasNext()) {
//                            String key = it.next();
//                            ManagerUserInfo[] array = new Gson().fromJson(groupListobj.optString(key), ManagerUserInfo[].class);
////                            ManagerUserInfo managerUserInfo = new ManagerUserInfo();
//                            int arynum = 0;
//                            for (int i = 0; i < array.length; i++) {
//                                ManagerUserInfo infoTmp = array[i];
//                                ManagerUserInfo infoTmp2 = new ManagerUserInfo();
//                                if (infoTmp.getUser() != null) {
//                                    arynum = array.length;
//                                } else {
//                                    arynum = 0;
//                                }
//                                if (i == 0) {
//                                    infoTmp2.setCurType(2);
//                                    infoTmp2.setGroupnum(arynum);
//                                    infoTmp2.setGroup(infoTmp.getGroup());
//                                    list.add(infoTmp2);
//                                    sumNum += arynum;
//                                }
//
//                                if (infoTmp.getUser() != null) {
//                                    if (!TextUtils.isEmpty(appendId) && infoTmp.getId().equals(appendId)) {
//                                        getActivity().runOnUiThread(new Runnable() {
//
//                                            @Override
//                                            public void run() {
//                                                //更新UI
//                                                noticeDialog = new PublicNoticeDialog(getActivity(), new View.OnClickListener() {
//                                                    @Override
//                                                    public void onClick(View v) {
//                                                        switch (v.getId()) {
//                                                            case R.id.ll_close:
//                                                            case R.id.btn_chancel_notice:
//                                                                noticeDialog.dismiss();
//                                                                break;
//                                                            case R.id.btn_save_notice:
//                                                                ManagerUserPermissionActivity.start(getActivity(), infoTmp, true);
//                                                                noticeDialog.dismiss();
//                                                                break;
//
//                                                        }
//                                                    }
//                                                }, 1, "提示", "添加成功，请与其联系登录系统",
//                                                        "暂不设置", "设置成员权限");
//                                                noticeDialog.show();
//                                            }
//                                        });
//                                    }
//                                    list.add(infoTmp);
//                                }
//                            }
//                        }
                        mData.clear();
                        mData.addAll(list);
                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                mAdapter.notifyDataSetChanged();
                                if (getActivity() instanceof ManagerListActivity) {
                                    ((ManagerListActivity) getActivity()).setTitleNum("管理人团队成员（" + sumNum + "人）");
                                }
                            }

                        });
                    }
                    str = "";
                }catch (Exception ex)
                {
                    ex.printStackTrace();
//                    runOnUiThread(new Runnable() {
//
//                        @Override
//                        public void run() {
//                            //更新UI
//                            Toast.makeText(PersonSettingOrgActivity.this, "保存失败", Toast.LENGTH_SHORT).show();
//
//                        }
//
//                    });
                }
            }
        });
    }


    public void addGroup(String groupname)
    {
        if(BankruptcyApp.tokeninfo == null|| BankruptcyApp.tokeninfo.getToken() == null)
        {
            return;
        }
        shapeLoadingDialog.setLoadingText("加载中...");
        shapeLoadingDialog.setCanceledOnTouchOutside(false);
        shapeLoadingDialog.show();
        OkHttpClient okHttpClient = new OkHttpClient();
//        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong()+"";
        String timestamp =System.currentTimeMillis()+"";
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken","");
        String userId = SPUtils.getInstance(Consts.SPNAME).getString("userId","");

        RequestBody requestBody = new FormBody.Builder()
                .add("appid","1000000001")
                .add("nonce",rom)
                .add("timestamp", timestamp)
                .add("token", BankruptcyApp.tokeninfo.getToken())
                .add("userToken",userToken)


                .add("projectId",mProID)
                .add("groupName", groupname)
                .build();

        String url = Consts.WEBURL_ADDGROUP;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                shapeLoadingDialog.dismiss();
                Log.d(TAG, "onFailure: " + e.getMessage());
                getActivity().runOnUiThread(new Runnable(){

                    @Override
                    public void run() {
                        //更新UI
                        Toast.makeText(getActivity(),"保存失败",Toast.LENGTH_SHORT).show();

                    }

                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, response.protocol() + " " +response.code() + " " + response.message());
                Headers headers = response.headers();
                shapeLoadingDialog.dismiss();
                for (int i = 0; i < headers.size(); i++) {
                    Log.d(TAG, headers.name(i) + ":" + headers.value(i));
                }


                String str = response.body().string();
                try{
                    JSONObject object = new JSONObject(str);
                    if(object.optInt("code") == 0)
                    {
                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                Toast.makeText(getActivity(), "保存成功", Toast.LENGTH_SHORT).show();

                            }

                        });
//                        finish();

                    }else {
                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                Toast.makeText(getActivity(), "保存失败", Toast.LENGTH_SHORT).show();

                            }

                        });

                    }
                    str = "";
                }catch (Exception ex)
                {
                    ex.printStackTrace();
                    getActivity().runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            //更新UI
                            Toast.makeText(getActivity(), "保存失败", Toast.LENGTH_SHORT).show();

                        }

                    });
                }
            }
        });
    }

    public void addUser(String groupId,String name,String phone)
    {
        if(BankruptcyApp.tokeninfo == null|| BankruptcyApp.tokeninfo.getToken() == null)
        {
            return;
        }
        shapeLoadingDialog.setLoadingText("加载中...");
        shapeLoadingDialog.setCanceledOnTouchOutside(false);
        shapeLoadingDialog.show();
        OkHttpClient okHttpClient = new OkHttpClient();
//        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong()+"";
        String timestamp =System.currentTimeMillis()+"";
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken","");
        String userId = SPUtils.getInstance(Consts.SPNAME).getString("userId","");

        RequestBody requestBody = new FormBody.Builder()
                .add("appid","1000000001")
                .add("nonce",rom)
                .add("timestamp", timestamp)
                .add("token", BankruptcyApp.tokeninfo.getToken())
                .add("userToken",userToken)


                .add("projectId", mProID)
                .add("groupId", groupId)
                .add("memberName", name)
                .add("memberMobile", phone)
                .build();

        String url = Consts.WEBURL_ADDMEMBER;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                shapeLoadingDialog.dismiss();
//                Log.d(TAG, "onFailure: " + e.getMessage());
                getActivity().runOnUiThread(new Runnable(){

                    @Override
                    public void run() {
                        //更新UI
                        Toast.makeText(getActivity(),"保存失败",Toast.LENGTH_SHORT).show();

                    }

                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, response.protocol() + " " +response.code() + " " + response.message());
                Headers headers = response.headers();
                shapeLoadingDialog.dismiss();
                for (int i = 0; i < headers.size(); i++) {
                    Log.d(TAG, headers.name(i) + ":" + headers.value(i));
                }


                String str = response.body().string();
                try{
                    final JSONObject object = new JSONObject(str);
                    if(object.optInt("code") == 0)
                    {
                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI

                                Toast.makeText(getActivity(), "保存成功", Toast.LENGTH_SHORT).show();
                                if(createUserDialog != null)
                                {
                                    createUserDialog.dismiss();
                                }
                            }

                        });
//                        finish();

                    }else {
                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                if("该成员已经添加到该组,请勿重复添加".equalsIgnoreCase(object.optString("msg")))
                                {
                                    createUserDialog.tv_have_user.setVisibility(View.VISIBLE);
                                }
                                Toast.makeText(getActivity(), "保存失败", Toast.LENGTH_SHORT).show();

                            }

                        });

                    }
                    str = "";
                }catch (Exception ex)
                {
                    ex.printStackTrace();
                    getActivity().runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            //更新UI
                            Toast.makeText(getActivity(), "保存失败", Toast.LENGTH_SHORT).show();

                        }

                    });
                }
            }
        });
    }


    public void delGroup(String groupId)
    {
        if(BankruptcyApp.tokeninfo == null|| BankruptcyApp.tokeninfo.getToken() == null)
        {
            return;
        }
        shapeLoadingDialog.setLoadingText("加载中...");
        shapeLoadingDialog.setCanceledOnTouchOutside(false);
        shapeLoadingDialog.show();
        OkHttpClient okHttpClient = new OkHttpClient();
//        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong()+"";
        String timestamp =System.currentTimeMillis()+"";
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken","");
        String userId = SPUtils.getInstance(Consts.SPNAME).getString("userId","");

        RequestBody requestBody = new FormBody.Builder()
                .add("appid","1000000001")
                .add("nonce",rom)
                .add("timestamp", timestamp)
                .add("token", BankruptcyApp.tokeninfo.getToken())
                .add("userToken",userToken)


                .add("groupId", groupId)
                .build();

        String url = Consts.WEBURL_DELETEGROUP;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                shapeLoadingDialog.dismiss();
//                Log.d(TAG, "onFailure: " + e.getMessage());
                getActivity().runOnUiThread(new Runnable(){

                    @Override
                    public void run() {
                        //更新UI
                        Toast.makeText(getActivity(),"保存失败",Toast.LENGTH_SHORT).show();

                    }

                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, response.protocol() + " " +response.code() + " " + response.message());
                Headers headers = response.headers();
                shapeLoadingDialog.dismiss();
                for (int i = 0; i < headers.size(); i++) {
                    Log.d(TAG, headers.name(i) + ":" + headers.value(i));
                }


                String str = response.body().string();
                try{
                    final JSONObject object = new JSONObject(str);
                    if(object.optInt("code") == 0)
                    {
                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI

                                Toast.makeText(getActivity(), "操作成功", Toast.LENGTH_SHORT).show();
//                                if(createUserDialog != null)
//                                {
//                                    createUserDialog.dismiss();
//                                }
                                getData();
                            }

                        });
//                        finish();

                    }else {
                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
//                                if("该成员已经添加到该组,请勿重复添加".equalsIgnoreCase(object.optString("msg")))
//                                {
//                                    createUserDialog.tv_have_user.setVisibility(View.VISIBLE);
//                                }
                                Toast.makeText(getActivity(),object.optString("msg") , Toast.LENGTH_SHORT).show();

                            }

                        });

                    }
                    str = "";
                }catch (Exception ex)
                {
                    ex.printStackTrace();
                    getActivity().runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            //更新UI
                            Toast.makeText(getActivity(), "保存失败", Toast.LENGTH_SHORT).show();

                        }

                    });
                }
            }
        });
    }


    public void delUser(String userId)
    {
        if(BankruptcyApp.tokeninfo == null|| BankruptcyApp.tokeninfo.getToken() == null)
        {
            return;
        }
        shapeLoadingDialog.setLoadingText("加载中...");
        shapeLoadingDialog.setCanceledOnTouchOutside(false);
        shapeLoadingDialog.show();
        OkHttpClient okHttpClient = new OkHttpClient();
//        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong()+"";
        String timestamp =System.currentTimeMillis()+"";
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken","");
//        String userId = SPUtils.getInstance(Consts.SPNAME).getString("userId","");

        RequestBody requestBody = new FormBody.Builder()
                .add("appid","1000000001")
                .add("nonce",rom)
                .add("timestamp", timestamp)
                .add("token", BankruptcyApp.tokeninfo.getToken())
                .add("userToken",userToken)


                .add("managersTeamId", userId)
                .build();

        String url = Consts.WEBURL_DELETEOTHERMEMBER;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                shapeLoadingDialog.dismiss();
//                Log.d(TAG, "onFailure: " + e.getMessage());
                getActivity().runOnUiThread(new Runnable(){

                    @Override
                    public void run() {
                        //更新UI
                        Toast.makeText(getActivity(),"保存失败",Toast.LENGTH_SHORT).show();

                    }

                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, response.protocol() + " " +response.code() + " " + response.message());
                Headers headers = response.headers();
                shapeLoadingDialog.dismiss();
                for (int i = 0; i < headers.size(); i++) {
                    Log.d(TAG, headers.name(i) + ":" + headers.value(i));
                }


                String str = response.body().string();
                try{
                    final JSONObject object = new JSONObject(str);
                    if(object.optInt("code") == 0)
                    {
                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI

                                Toast.makeText(getActivity(), "操作成功", Toast.LENGTH_SHORT).show();
                                getData();
                            }

                        });
//                        finish();

                    }else {
                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                if("该成员已经添加到该组,请勿重复添加".equalsIgnoreCase(object.optString("msg")))
                                {
                                    createUserDialog.tv_have_user.setVisibility(View.VISIBLE);
                                }
                                Toast.makeText(getActivity(), "保存失败", Toast.LENGTH_SHORT).show();

                            }

                        });

                    }
                    str = "";
                }catch (Exception ex)
                {
                    ex.printStackTrace();
                    getActivity().runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            //更新UI
                            Toast.makeText(getActivity(), "保存失败", Toast.LENGTH_SHORT).show();

                        }

                    });
                }
            }
        });
    }

}
